window.addEvent('domready', function(event){
	fetcher.initialize();
});

var fetcher = {
		images: new Array(),
		numberOfImages: 0,
		imageIndex: 0,
		initialize: function(){
			$('nextImage').addEvent('click', fetcher.nextImage);
			$('prevImage').addEvent('click', fetcher.prevImage);
			$('fetchButton').addEvent('click', fetcher.fetchLink);
		},
		fetchLink: function(event){
			var r = new Request.JSON({
				url: '../../AjaxLinkFetcher.php',
				data: {
	                url: $('fetchInput').value
	            },
	            onSuccess: function(answer){
	            	fetcher.numberOfImages = answer.images.length;
	                if(fetcher.numberOfImages > 0){
	                	$('imagePreview').src = answer.images[0];
	                	fetcher.images = answer.images;
	                	fetcher.imageIndex = 0;
	                	$('numberOfImages').innerHTML = fetcher.numberOfImages;
	                	$('imageIndex').innerHTML = 1;
	                }
	                else{
	                	$('imagePreview').src = '';
	                	fetcher.images = new Array();
	                	$('numberOfImages').innerHTML = 0;
	                	$('imageIndex').innerHTML = 0;
	                }
	                $('title').innerHTML = answer.title;
	                $('description').innerHTML = answer.description;
	            }
			});
			r.send();
		},
		nextImage: function(){
			if(fetcher.imageIndex < fetcher.numberOfImages - 1){
				$('imagePreview').src = fetcher.images[++fetcher.imageIndex];
				$('imageIndex').innerHTML = fetcher.imageIndex+1;
			}
		},
		prevImage: function(){
			if(fetcher.imageIndex > 0){
				$('imagePreview').src = fetcher.images[--fetcher.imageIndex];
				$('imageIndex').innerHTML = fetcher.imageIndex+1;
			}
		}
};